<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use DB;

class UserController extends Controller
{
    //添加管理员
    public function getRegister(){
        $roles = DB::table('roles')->get();
        foreach($roles as $k=>$v ){
            //切割
            $temp = explode(',',$v->pid);
            //数据替换
            foreach($temp as $key => $per){
                $data = DB::table('privileges')->select('pname')->where('pid',$per)->first();
                $temp[$key] = $data-> pname;
            }
            $roles[$k]->pid = $temp;
        };
        return view('admin.register',['roles'=>$roles]);
    }

    //处理添加管理员页面提交的数据
    public function postRegister(Request $req){
        $this->validate($req,[
            'name'=>'required|unique:admins,name',
            'password'=>'required|min:6',
            'rid'=>'required'
            ]);
        unset($_POST['_token']);
        foreach($_POST as $c ){
            if(!$c){
                return $c.'不允许为空';
            }
        }
        $_POST['password'] = md5($_POST['name'].$_POST['password']);
        DB::table('admins')->insert($_POST);

        return redirect('admins/adminlist');
    }

    //登录页面加载
    public function getLogin(){
        return view('admin.login');
    }

    //验证登录
    public function postLogin(Request $r){
        unset($_POST['_token']);
        foreach($_POST as $c ){
            if(!$c){
                return $c.'不允许为空';
            }
        }
        $admin = DB::table('admins')->where('name',$_POST['name'])->first();
        if(!$admin){
            return '该用户名不存在';
        }
        $_POST['password'] = md5($_POST['name'].$_POST['password']);
        if($_POST['password'] != $admin->password){
            return '用户名或密码错误';
        }

        //写入session
        session(['adminname' => $_POST['name'],'password'=>$_POST['password'],'role'=>$admin->rid]);
        $direction = session('direction')?session('direction'):'admins/adminlist';
        return redirect($direction);
    }

    //管理员列表
    public function adminlist(){
        $admin = DB::table('admins')->leftjoin('roles','admins.rid','=','roles.rid')->get(['admins.*','roles.rname']);
        return view('admin.adminlist',['admin'=>$admin]);
    }

    //退出登录
    public function getLogout(Request $request){
        $request->session()->forget('adminname');
        $request->session()->forget('password');
        $request->session()->forget('role');
        return redirect('admins/login');
    }
}
